/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */

package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.form.StringPropertySelectionModel;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.IPage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.crm.model.Process;
import com.crm.model.User;
import com.crm.model.Contact;
import com.crm.service.IProcessService;
import com.crm.service.IContactService;
import com.crm.web.util.Tools;
import com.crm.web.util.Constants;
import com.javaforge.tapestry.spring.annotations.InjectSpring;

import java.util.Date;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class ProcessModify extends BasePage implements PageBeginRenderListener {

    private static Log log = LogFactory.getLog(ProcessModify.class);
    private boolean modify;
    private boolean handle;
    private Contact contact;

    @InjectSpring("processService")
    public abstract IProcessService getProcessService();

    @InjectSpring("contactService")
    public abstract IContactService getContactManager();

    @InjectPage("ProcessInfo")
    public abstract ProcessInfo getProcessInfoPage();

    @InjectPage("ProcessHistory")
    public abstract ProcessHistory getProcessHistoryPage();

    @InjectPage("ProcessNew")
    public abstract ProcessNew getProcessNewPage();

    @Bean
    public abstract ValidationDelegate getDelegate();

    @InjectState("userSession")
    public abstract User getUserSession();

    public abstract String getSerialNum();

    public abstract Date getCommuneTime();

    public abstract String getConclusionSelected();

    public abstract String getCommuneWaySelected();

    public abstract String getCommuneResult();

    public abstract String getComment();

    // Model's value of drop-down list box
    public IPropertySelectionModel getConclusionSelectionModel() {
        return new StringPropertySelectionModel(Constants.REMIND_DAYS);
    }

    public IPropertySelectionModel getCommuneWaySelectionModel() {
        return new StringPropertySelectionModel(Constants.COMMUNE_WAY);
    }

    public IPropertySelectionModel getCommuneResultModel() {
        return new StringPropertySelectionModel(Constants.COMMUNE_RESULT);
    }

    // transfer value from selected drop-down list
    public int translate(String selected) {
        if (selected.equals("1天")) return 1;
        else if (selected.equals("2天")) return 2;
        else if (selected.equals("3天")) return 3;
        else if (selected.equals("4天")) return 4;
        else if (selected.equals("5天")) return 5;
        else if (selected.equals("6天")) return 6;
        else if (selected.equals("7天")) return 7;
        else if (selected.equals("8天")) return 8;
        else if (selected.equals("9天")) return 9;
        else if (selected.equals("10天")) return 10;
        else if (selected.equals("11天")) return 11;
        else if (selected.equals("12天")) return 12;
        else if (selected.equals("13天")) return 13;
        else if (selected.equals("14天")) return 14;
        else if (selected.equals("15天")) return 15;
        else if (selected.equals("20天")) return 20;
        else if (selected.equals("25天")) return 25;
        else if (selected.equals("30天")) return 30;
        else if (selected.equals("40天")) return 40;
        else if (selected.equals("50天")) return 50;
        else if (selected.equals("60天")) return 60;
        else return 0;
    }

    @Persist
    public abstract Process getProcess();

    public abstract void setProcess(Process process);

    @Persist
    public abstract String getSourcePage();

    public abstract void setSourcePage(String flag);

    public void setModify(boolean modify) {
        this.modify = modify;
    }

    public boolean isModify() {
        return modify;
    }

    public boolean isHandle() {
        return handle;
    }

    public void setHandle(boolean handle) {
        this.handle = handle;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    //    public String getContactName() {
//        String contactId = getProcess().getContactId();
//        return getContactManager().getContactById(contactId).getContactName();
//    }

    public String goback() {
        return getSourcePage();
    }

    public void pageBeginRender(PageEvent event) {
        if (null == getUserSession() || null == getProcess()) {
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
        }

        setContact(getContactManager().getContactById(getProcess().getContactId()));

        // control modify form show
        String currentLoginUser = getUserSession().getUserCode();
        String owner = getProcess().getUser().getUserCode();
        if (!currentLoginUser.equals(owner) || getSourcePage().equals("ProcessHistory")) {
            setModify(false);
            setHandle(false);
        } else if (getSourcePage().equals("ProcessRemind") || getSourcePage().equals("UserRemind")) {
            setModify(false);
            setHandle(true);
        } else {
            setModify(true);
            setHandle(false);
        }
    }

    public String getShowIsHandle() {
        return getProcess().getIsHandle().equals("0") ? "未处理" : "已处理";
    }

    public String infoSubmit() {
        try {
            if (null == getSerialNum() &&
                (null == getCommuneResult() || "---请选择---".equals(getCommuneResult())) &&
                (null == getCommuneWaySelected() || "---请选择---".equals(getCommuneWaySelected())) &&
                (null == getConclusionSelected() || "---请选择---".equals(getConclusionSelected())) &&
                null == getCommuneTime() && null == getComment()) {
                getDelegate().record("沟通信息未发生改变", ValidationConstraint.CONSISTENCY);
                return getPageName();
            }

            Process process = getProcess();

            if (getSerialNum() != null) process.setSerialNum(getSerialNum());
            if (!getCommuneResult().equals("---请选择---"))
                process.setCommuneResult(getCommuneResult());
            if (!getCommuneWaySelected().equals("---请选择---"))
                process.setCommuneWay(getCommuneWaySelected());
            if (null != getConclusionSelected() && !"---请选择---".equals(getConclusionSelected()))
                process.setConclusion(getConclusionSelected());

            if (getCommuneTime() != null) {
                String currentDate = Tools.formatDate(getCommuneTime(), Tools.DATEANDTIME);
                process.setCommuneTime(currentDate);
            }

            Integer processDays = translate(getConclusionSelected());
            process.setStepNum(processDays);

            if (processDays != 0)
                process.setRemindDate(Tools.getRemindInfo(processDays));
            else process.setRemindDate("N");

            String commentString = getComment() == null ? "none" : getComment();
            process.setComment(commentString);

            if (getComment() != null) process.setComment(getComment());

            getProcessService().create(process);

            getDelegate().record("已修改", ValidationConstraint.CONSISTENCY);
            log.info(getUserSession().getUsername() + " : Modify process info! \n" + process.toString());

            return "ProcessModify";
        }
        catch (Exception e) {
            String exceptionString = getUserSession().getUsername() + " : The exception happened when modify process info : " + e.getMessage();
            log.warn(exceptionString);
            e.printStackTrace();
            getDelegate().record(exceptionString, ValidationConstraint.CONSISTENCY);
            return getPageName();
        }
    }

    public String signHandle() {
        Process p = getProcess();
        p.setIsHandle("1");
        getProcessService().update(p);
        log.info(getUserSession().getUsername() + ": Handle process info -> " + p.toString());
        return getPageName();
    }

    public IPage addProcessInfo() {
        ProcessNew page = getProcessNewPage();
        page.setContactInfo(contact);
        return page;
    }    
}

